#    Copyright 2012 New Mexico EPSCoR
#
#    This file is part of Teacher's P.E.T.
#
#    Teacher's P.E.T. is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Teacher's P.E.T. is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Teacher's P.E.T..  If not, see <http://www.gnu.org/licenses/>.
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.testcases import to_list
from django.test.client import Client
from django.contrib.auth.models import User

from apps.forum.models import *
from apps.course.models import Course
from apps.participants.models import CourseParticipant


        
class ForumTestCaseBase(TestCase):
    def enable_logging(self):
        logging.disable(0)
    
    def disable_logging(self):
        logging.disable(logging.CRITICAL)
        
    def assertInMessages(self, response, expected_msg, msg_prefix=''):
        if msg_prefix:
            msg_prefix += ": "
        
        expected_msg_found = False
        Messages = []
        if response.context and 'messages' in response.context and response.context['messages']:
            Messages.append(response.context['messages'])
            for msg in response.context['messages']:
                if expected_msg in str(msg): expected_msg_found = True; #print "Found '%s' in context" % expected_msg
        if not expected_msg_found:
            if response.cookies and 'messages' in response.cookies and response.cookies['messages']:
                Messages.append(response.cookies['messages'])
                if expected_msg in response.cookies['messages'].value: expected_msg_found = True; #print "Found '%s' in cookies" % expected_msg
                
        self.assertTrue(expected_msg_found,msg_prefix + "Phrase '%s' not found in messages: %s" % (expected_msg,Messages))
    
    def assertInFormError(self, response, form, field, errors, msg_prefix=''):
        """
        Asserts that a form used to render the response contains a phrase in a field
        error.
        """
        if msg_prefix:
            msg_prefix += ": "

        # Put context(s) into a list to simplify processing.
        contexts = to_list(response.context)
        if not contexts:
            self.fail(msg_prefix + "Response did not use any contexts to "
                      "render the response")

        # Put error(s) into a list to simplify processing.
        errors = to_list(errors)

        # Search all contexts for the error.
        found_form = False
        for i,context in enumerate(contexts):
            if form not in context:
                continue
            found_form = True
            for err in errors:
                if field:
                    if field in context[form].errors:
                        field_errors = '\n'.join(context[form].errors[field])
                        self.assertTrue(err in field_errors,
                            msg_prefix + "The field '%s' on form '%s' in"
                            " context %d does not contain the error '%s'"
                            " (actual errors: %s)" %
                                (field, form, i, err, repr(context[form].errors[field])))
                    elif field in context[form].fields:
                        self.fail(msg_prefix + "The field '%s' on form '%s'"
                                  " in context %d contains no errors" %
                                      (field, form, i))
                    else:
                        self.fail(msg_prefix + "The form '%s' in context %d"
                                  " does not contain the field '%s'" %
                                      (form, i, field))
                else:
                    non_field_errors = '\n'.join(context[form].non_field_errors())
                    self.assertTrue(err in non_field_errors,
                        msg_prefix + "The form '%s' in context %d does not"
                        " contain the non-field error '%s'"
                        " (actual errors: %s)" %
                            (form, i, err, context[form].non_field_errors()))
        if not found_form:
            self.fail(msg_prefix + "The form '%s' was not used to render the"
                      " response" % form)
            
    def setUp(self):
        #Turn off logging
        self.disable_logging()
        
        #Create the test course
        self.course1 = Course(course_id='forum_test_course',course_title='Forum Test Course'); self.course1.save()
        
        #Create the test users - students
        self.student1 = User(first_name='student1', last_name='user', username='student1', email='test_user1@no.com'); self.student1.set_password("student"); self.student1.save()
        self.student2 = User(first_name='student2', last_name='user', username='student2', email='test_user2@no.com'); self.student2.set_password("student"); self.student2.save()
        self.student3 = User(first_name='student3', last_name='user', username='student3', email='test_user3@no.com'); self.student3.set_password("student"); self.student3.save()
        self.student4 = User(first_name='student4', last_name='user', username='student4', email='test_user4@no.com'); self.student4.set_password("student"); self.student4.save()
        self.student5 = User(first_name='student5', last_name='user', username='student5', email='test_user5@no.com'); self.student5.set_password("student"); self.student5.save()
        
        #Create the test users - instructors
        self.instructor1 = User(first_name="instructor1", last_name="instructor", username="instructor1", email="instructor1@no.com"); self.instructor1.set_password("instructor"); self.instructor1.save()
        self.instructor2 = User(first_name="instructor2", last_name="instructor", username="instructor2", email="instructor2@no.com"); self.instructor2.set_password("instructor"); self.instructor2.save()
        
        #Create the test users - assistants
        self.assistant1 = User(first_name="assistant1", last_name="assistant", username="assistant1", email="assistant1@no.com"); self.assistant1.set_password("assistant"); self.assistant1.save()
        self.assistant2 = User(first_name="assistant2", last_name="assistant", username="assistant2", email="assistant2@no.com"); self.assistant2.set_password("assistant"); self.assistant2.save()

        #Overwrite the self variables with course participants (since user can be accessed as .user afterwards)
        self.student1 = CourseParticipant(user=self.student1,course=self.course1,status="STUDENT"); self.student1.save()
        self.student2 = CourseParticipant(user=self.student2,course=self.course1,status="STUDENT"); self.student2.save()
        self.student3 = CourseParticipant(user=self.student3,course=self.course1,status="STUDENT"); self.student3.save()
        self.student4 = CourseParticipant(user=self.student4,course=self.course1,status="STUDENT"); self.student4.save()
        self.student5 = CourseParticipant(user=self.student5,course=self.course1,status="STUDENT"); self.student5.save()

        self.instructor1 = CourseParticipant(user=self.instructor1,course=self.course1,status="INSTRUCTOR"); self.instructor1.save()
        self.instructor2 = CourseParticipant(user=self.instructor2,course=self.course1,status="INSTRUCTOR"); self.instructor2.save()

        self.assistant1 = CourseParticipant(user=self.assistant1,course=self.course1,status="ASSISTANT"); self.assistant1.save()
        self.assistant2 = CourseParticipant(user=self.assistant2,course=self.course1,status="ASSISTANT"); self.assistant2.save()
        
        #Also make instructor1 an instructor for the __default course
        CP = CourseParticipant(user=self.instructor1.user,course=Course.find(None),status="INSTRUCTOR"); CP.save()
        
        #Log everone in
        self.student1.client = Client(enforce_csrf_checks=False); self.student1.client.login(username='student1',password='student')
        self.student2.client = Client(enforce_csrf_checks=False); self.student2.client.login(username='student2',password='student')
        self.student3.client = Client(enforce_csrf_checks=False); self.student3.client.login(username='student3',password='student')
        self.student4.client = Client(enforce_csrf_checks=False); self.student4.client.login(username='student4',password='student')
        self.student5.client = Client(enforce_csrf_checks=False); self.student5.client.login(username='student5',password='student')
        self.instructor1.client = Client(enforce_csrf_checks=False); self.instructor1.client.login(username='instructor1',password='instructor')
        self.instructor2.client = Client(enforce_csrf_checks=False); self.instructor2.client.login(username='instructor2',password='instructor')
        self.assistant1.client = Client(enforce_csrf_checks=False); self.assistant1.client.login(username='assistant1',password='assistant')
        self.assistant2.client = Client(enforce_csrf_checks=False); self.assistant2.client.login(username='assistant2',password='assistant')
    
        #Create a forum
        self.forum = Forum(title="The test forum"); self.forum.save()
        self.course1.forum = self.forum; self.course1.save()
        
class ForumThreadTestCaseBase(ForumTestCaseBase):
    def setUp(self):
        super(ForumThreadTestCaseBase,self).setUp()
        
        self.thread1 = ForumThread(forum=self.course1.forum,title="The first thread in the test forum"); self.thread1.save()
        self.thread1.entry1 = ForumEntry(thread=self.thread1,author=self.instructor1,entry="First!"); self.thread1.entry1.save()
        self.thread1.entry2 = ForumEntry(thread=self.thread1,author=self.student1,entry="First!\n Ahhh, darn..."); self.thread1.entry2.save()
        self.thread1.entry3 = ForumEntry(thread=self.thread1,author=self.instructor2,entry="Just for that, 50 points from Gryffindor"); self.thread1.entry3.save()
        self.thread1.first_entry = self.thread1.entry1; self.thread1.save()
        self.thread1.last_entry = self.thread1.entry3; self.thread1.save()
        
        self.thread2 = ForumThread(forum=self.course1.forum,title="Homework due tuesday"); self.thread2.save()
        self.thread2.entry1 = ForumEntry(thread=self.thread2,author=self.instructor1,entry="The assignment has been posted"); self.thread2.entry1.save()
        self.thread2.entry2 = ForumEntry(thread=self.thread2,author=self.student1,entry="I don't understand question 3"); self.thread2.entry2.save()
        self.thread2.entry3 = ForumEntry(thread=self.thread2,author=self.instructor2,entry="Read it using those blue/red 3D glasses."); self.thread2.entry3.save()
        self.thread2.first_entry = self.thread2.entry1; self.thread2.save()
        self.thread2.last_entry = self.thread2.entry3; self.thread2.save()
        
class ForumMessageTestCaseBase(ForumTestCaseBase):
    def setUp(self):
        super(ForumMessageTestCaseBase,self).setUp()
        
        self.msg1 = ForumPrivateMessage(forum=self.course1.forum)
        self.msg1.sender = self.student1.user
        self.msg1.recipient = self.student2.user
        self.msg1.message = "This is the first message in a conversation between student1 and student2"
        self.msg1.response_to = None
        self.msg1.mark_sent()
        self.msg1.save()
        
        self.msg2 = ForumPrivateMessage(forum=self.course1.forum)
        self.msg2.sender = self.student1.user
        self.msg2.recipient = self.instructor1.user
        self.msg2.message = "This is a draft message from student1 to instructor1"
        self.msg2.response_to = None
        self.msg2.save()
        
        self.msg3 = ForumPrivateMessage(forum=self.course1.forum)
        self.msg3.sender = self.student1.user
        self.msg3.recipient = self.student2.user
        self.msg3.message = "Here's that thing you asked for when you asked me for that one thing about the stuff"
        self.msg3.response_to = None
        self.msg3.mark_sent()
        self.msg3.mark_deleted()
        self.msg3.save()
        
        self.msg4 = ForumPrivateMessage(forum=self.course1.forum)
        self.msg4.sender = self.student2.user
        self.msg4.recipient = self.student1.user
        self.msg4.message = "This is a message from student2 to student1. Your shoelace is untied..."
        self.msg4.response_to = None
        self.msg4.mark_sent()
        self.msg4.save()
                